/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.boruan.shengtangfeng.core.utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
 * 
 * @author ThinkGem
 * @version 2013-05-22
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    private static Logger logger = LoggerFactory.getLogger(StringUtils.class);

    private static final String CHARSET_NAME = "UTF-8";

    /**
     * 去除富文本的标签
     * @param content
     * @return
     */
    public static String dealContent(String content){
        String regx = "(<.+?>)|(</.+?>)";
        Matcher matcher = Pattern.compile(regx).matcher(content);
        while (matcher.find()){
            // 替换图片
            content= matcher.replaceAll("").replace(" ", "");
        }

        return content;
    }
    public static boolean checkPassword(String password) {
        String pattern = "^[a-zA-Z0-9]+$";
        return Pattern.matches(pattern, password);
    }
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public static String lowerFirst(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            return str.substring(0, 1).toLowerCase() + str.substring(1);
        }
    }

    public static String upperFirst(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            return str.substring(0, 1).toUpperCase() + str.substring(1);
        }
    }

    /**
     * 转换为字节数组
     *
     * @param
     * @return
     */
    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return EMPTY;
        }
    }

    /**
     * 转换为字节数组
     * 
     * @param str
     * @return
     */
    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 缩略字符串（不区分中英文字符）
     * 
     * @param str    目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : str.toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val) {
        if (val == null) {
            return 0D;
        }
        try {
            return Double.valueOf(trim(val.toString()));
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val) {
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val) {
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val) {
        return toLong(val).intValue();
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 创建指定数量的随机字符串
     *
     * @param numberFlag 是否是数字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length) {
        String retStr = null;
        String strTable = numberFlag ? "1234567890" : "1234567890";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

    /**
     * 对象转换字符串
     * 
     * @param obj
     * @return
     */
    public static String getStr(Object obj) {
        if (obj == null) {
            return "";
        } else {
            String str = obj.toString();
            if (str == null) {
                return "";
            } else {
                return str.trim();
            }
        }
    }

    /**
     * 生成验证码
     * 
     * @return
     */
    public static String createCharacter() {
        char[] codeSeq = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);// random.nextInt(10));
            s.append(r);
        }
        return s.toString();
    }

    /**
     * 创建数字字符串
     * 
     * @param len
     * @return
     */
    public static String createNumber(int len) {
        char[] codeSeq = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);// random.nextInt(10));
            s.append(r);
        }
        return s.toString();
    }

    /**
     * isRealBlank
     * 
     * @param str
     * @return
     */
    public static boolean isRealBlank(String str) {
        boolean flag;
        if (str == null || StringUtils.isBlank(str) || ("null").equals(str) || "(null)".equals(str) || str.equals("")) {
            flag = true;
        } else {
            flag = false;
        }
        return flag;
    }

    /**
     * replaceBlank(去除字符串中的空格、回车、换行符、制表符) @Title: replaceBlank @author String
     * 返回类型 @throws
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
//    	if (isBlank(str)) {
//			return false;
//		}
//    	if (str.length() > 20||str.length() < 11) {
//			return false;
//		}
//    	if (str.length() == 11) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
//		}
//        return true;
    }

    /**
     * 检查整数
     * 
     * @param num
     * @param type "0+" :非负整数 "+" :正整数 "-0" :非正整数 "-" :负整数 "" :整数
     * @return
     */
    public static boolean checkNumber(String num, String type) {
        if (num == null) {
            return false;
        }
        String eL = "";
        if (type.equals("0+"))
            eL = "^\\d+$";// 非负整数
        else if (type.equals("+"))
            eL = "^\\d*[1-9]\\d*$";// 正整数
        else if (type.equals("-0"))
            eL = "^((-\\d+)|(0+))$";// 非正整数
        else if (type.equals("-"))
            eL = "^-\\d*[1-9]\\d*$";// 负整数
        else
            eL = "^-?\\d+$";// 整数
        Pattern p = Pattern.compile(eL);
        Matcher m = p.matcher(num);
        boolean b = m.matches();
        return b;
    }

    /**
     * 获取字符串长度，中文字符长度为2
     * 
     * @param s
     * @return
     */
    public static int length(String s) {
        if (s == null)
            return 0;
        char[] c = s.toCharArray();
        int len = 0;
        for (int i = 0; i < c.length; i++) {
            len++;
            if (!isLetter(c[i])) {
                len++;
            }
        }
        return len;
    }

    /**
     * 判断是否是中文字符
     * 
     * @param c
     * @return
     */
    public static boolean isLetter(char c) {
        int k = 0x80;
        return c / k == 0 ? true : false;
    }

    /**
     * 过滤特殊字符
     * 
     * @param str
     * @return
     */
    public static String StringFilter(String str) {
        // 只允许字母和数字 //
//      String regEx ="[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（） _——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String stt = m.replaceAll("").trim();
        String result = str.replaceAll("\\\\", "");
        return result;
    }

    /**
     * 改变格式
     */
    public static String changStr(String str) {
        if (str == null || str.equals("") || str.length() <= 0) {
            return "";
        }
        str = str.replaceAll("\"", " ");
        return "\"" + str + "\"";
    }

    /**
     * 生成code码
     * 
     * @param lastCode 上一个code
     * @param count    生成数量
     */
    public static List<String> code(String lastCode, Long count) {
        List<String> list = new ArrayList<>();
        // 字符集
        String[] base = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i",
                "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
        String[] lastCodeArr = lastCode.split("");
        // 索引
        Long index = 0L;
        String s = "0123456789abcdefghijklmnopqrstuvwxyz";
        int jj = s.indexOf(lastCodeArr[0]);
        int kk = s.indexOf(lastCodeArr[1]);
        int ll = s.indexOf(lastCodeArr[2]);
        int mm = s.indexOf(lastCodeArr[3]);
        int nn = s.indexOf(lastCodeArr[4]);
        int oo = s.indexOf(lastCodeArr[5]);

        for (int j = jj; j < 36; j++) {
            for (int k = kk; k < 36; k++) {
                for (int l = ll; l < 36; l++) {
                    for (int m = mm; m < 36; m++) {
                        for (int n = nn; n < 36; n++) {
                            for (int o = oo; o < 36; o++) {
                                index++;
                                String code = base[j] + base[k] + base[l] + base[m] + base[n] + base[o];
                                if (base[j].equals(base[k]) && base[j].equals(base[l]) && base[j].equals(base[m])
                                        && base[j].equals(base[n]) && base[j].equals(base[o])) {// 不可用，每個字符相同
                                    // 具体逻辑，保存数据库或只是打印
                                    // System.out.println("不可用 : " + code);
                                } else {// 可用
                                        // 具体逻辑，保存数据库或只是打印
                                        // System.out.println("当前索引是 : " + index + " ===== 当前值为 : " + code);
                                    list.add(code);
                                }
                                if (list.size() == (count + 1)) {
                                    list.remove(0);
                                    return list;
                                }
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 生成验证码 纯数字
     * 
     * @return
     */
    public static String createCharacterNumber() {
        char[] codeSeq = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        Random random = new Random();
        StringBuilder s = new StringBuilder();
        int count = 1;
        while (true) {
            String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);// random.nextInt(10));
            if (count == 1 && "0".equals(r)) {
                continue;
            }
            s.append(r);
            if (count == 6) {
                break;
            }
            count++;
        }
        return s.toString();
    }

    /**
     * 判断字段是否为空，为空返回空字符串，不为空返回数据
     * 
     * @param str
     * @return
     */
    public static String isNull(String str) {
        if (str == null || str.equals("null")) {
            return "";
        } else {
            return str;
        }
    }

    /**
     * @author: lihaicheng
     * @Description: 验证码验证
     * @date:2020年3月10日 上午11:14:10
     */
    public static Boolean isValidate(String code1, String code2) {
        if (isRealBlank(code1) || isRealBlank(code2)) {
            return false;
        }
        if (code1.equals(code2)) {
            return true;
        }
        return false;
    }

    /**
     * @author: lihaicheng
     * @Description: 生成随机用户名，数字和字母组成
     * @date:2020年3月10日 上午11:14:10
     */
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        // 参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
//    public static void main(String[] args) {
//        String pattern = "^[a-zA-Z0-9]+$";
//        System.out.println(); Pattern.matches(pattern, "");
//    }
}
